const db = require('./db');

async function initDatabase() {
  try {
    // 创建用户表
    await db.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id VARCHAR(36) PRIMARY KEY,
        username VARCHAR(255) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // 创建函数表
    await db.execute(`
      CREATE TABLE IF NOT EXISTS functions (
        id VARCHAR(36) PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        version VARCHAR(50) NOT NULL DEFAULT 'v1.0.0',
        description TEXT,
        timeout INT NOT NULL DEFAULT 30,
        handler VARCHAR(255) NOT NULL,
        image VARCHAR(255) NOT NULL,
        env JSON,
        limits JSON,
        requests JSON,
        code LONGTEXT,
        published BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

    // 创建实例表
    await db.execute(`
      CREATE TABLE IF NOT EXISTS instances (
        id VARCHAR(36) PRIMARY KEY,
        function_id VARCHAR(36) NOT NULL,
        status ENUM('Running', 'Stopped') NOT NULL DEFAULT 'Stopped',
        url VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (function_id) REFERENCES functions(id) ON DELETE CASCADE
      )
    `);

    console.log('数据库初始化完成');
  } catch (error) {
    console.error('数据库初始化失败:', error);
  } finally {
    await db.end();
  }
}

initDatabase();